<template>
  <page-view class="register">
    <page-header title="注册" :show-back="true"></page-header>
    <div class="content-box">
      <van-form ref="registerForm">
        <van-cell-group inset>
          <van-field
            v-model="userInfoForm.nickName"
            name="nickName"
            label="昵称"
            placeholder="昵称"
            :rules="[
              { required: true, message: '请填写昵称', trigger: 'onBlur' },
              {
                validator: validatorNick,
                message: '昵称不可用',
                trigger: 'onBlur',
              },
            ]"
          />
          <van-field
            v-model="userInfoForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[
              { required: true, message: '请填写密码', trigger: 'onBlur' },
              { validator: validatorPassword },
            ]"
          />
          <van-field
            v-model="userInfoForm.confirm_pwd"
            type="password"
            name="confirm_pwd"
            label="确认密码"
            placeholder="确认密码"
            :rules="[
              { required: true, message: '请填写确认密码', trigger: 'onBlur' },
              { validator: validatorConfirm_pwd },
            ]"
          />
          <van-field
            v-model="userInfoForm.user_phone"
            type="text"
            name="user_phone"
            label="手机号码"
            placeholder="手机号码"
            :rules="[
              { required: true, message: '请填写手机号码', trigger: 'onBlur' },
              {
                pattern: /^1([358][0-9]|4[678]|7[123])[0-9]{8}$/,
                message: '手机号码格式不对',
              },
              {
                validator: validatorPhone,
                message: '手机号码已注册',
                trigger: 'onBlur',
              },
            ]"
          />
          <van-field
            v-model="userInfoForm.user_email"
            type="email"
            name="user_email"
            label="电子邮箱"
            placeholder="电子邮箱"
            :rules="[
              { required: true, message: '请填写电子邮箱', trigger: 'onBlur' },
            ]"
          />
          <van-field name="user_sex" label="性别">
            <template #input>
              <van-radio-group
                v-model="userInfoForm.user_sex"
                direction="horizontal"
              >
                <van-radio name="男">男</van-radio>
                <van-radio name="女">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            name="uploader"
            label="头像上传"
            v-model="userInfoForm.user_photo"
            :rules="[
              { required: true, message: '请上传头像', trigger: 'onBlur' },
            ]"
          >
            <template #input>
              <van-uploader
                v-model="fileList"
                :after-read="afterRead"
                :max-count="1"
              />
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px">
          <van-button
            round
            block
            type="primary"
            @click="submitRegister"
            :disabled="isLoading"
            :loading="isLoading"
            loading-text="正在注册"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </page-view>
</template>

<script setup>
import { reactive, ref, watch } from "vue";
import api from "../utils/api";
import MD5 from "md5.js";
import { showNotify } from "vant";
import { useRouter } from "vue-router";
const router = useRouter();
const isLoading = ref(false);

const userInfoForm = reactive({
  nickName: "",
  password: "",
  confirm_pwd: "",
  user_phone: "",
  user_email: "",
  user_sex: "女",
  user_photo: "",
});

const validatorNick = async (val) => {
  let result = await api.userInfo.checkNickName(val);
  if (result.status === "fail") return false;
};
const validatorPhone = async (val) => {
  let result = await api.userInfo.checkUserPhone(val);
  if (result.status === "fail") return false;
};
const validatorPassword = (val) => {
  if (val.length < 6 || val.length > 18)
    return "密码的长度不对，需要再6-18位之间";
};
const validatorConfirm_pwd = (val) => {
  if (userInfoForm.password != userInfoForm.confirm_pwd)
    return "两次输入的密码不一致";
};

const fileList = ref([]);
const afterRead = async (file) => {
  // 此时可以自行将文件上传至服务器
  let result = await api.userInfo.uploadUserPhoto(file.file);
  userInfoForm.user_photo = result;
};

// 提交注册按钮事件
const registerForm = ref(null);
const submitRegister = async () => {
  try {
    await registerForm.value.validate();
    let { nickName, user_sex, user_phone, user_email, user_photo, password } =
      userInfoForm;
    password = new MD5().update(password).digest("hex");
    isLoading.value = true;
    let result = await api.userInfo.register({
      nickName,
      user_sex,
      user_phone,
      user_email,
      user_photo,
      password,
    });
    showNotify({ type: "success", message: "注册成功" });
    router.replace({ name: "login" });
  } catch (error) {
  } finally {
    isLoading.value = false;
  }
};

// watch(
//   () => userInfoForm.user_sex,
//   (newV, oldV) => {
//     console.log(oldV + "---" + newV);
//     console.log(userInfoForm.user_sex);
//   }
// );
</script>

<style lang="scss" scoped>
</style>